//  获取文章分类
$.ajax({
  type: 'get',
  url: '/categories',
  success: function(response) {
    let html = template('showPostCateTpl', {data: response})
    $('#showcategory').html(html)
  }
})
// 表单提交
$('#postsForm').on('submit', function() {
  let formData = $(this).serialize()
  $.ajax({
    type:"post",
    url: '/posts',
    data: formData,
    success: function(response) {
     location.reload()
    },
    error: function(response) {
      console.log(response)
    }
  })
  return false
})
//  文件上传
$('#postImg').on('change', function() {
  let formData = new FormData()
  formData.append('avatar', this.files[0])
  $.ajax({
    type: 'post',
    url: '/upload',
    data: formData,
    processData: false,
    contentType: false,
    success: function(response) {
      $('#postImgHidden').val(response[0].avatar)
    }
  })
})
//  根据id修改文章
function getId() {
  let id = location.search
  let num = id.indexOf('=')
  id = id.substr(num+1)
  return id
}
let id = getId()
if (id) {
  $.ajax({
    type: 'get',
    url: '/posts/'+id,
    success: function(response) {
      $.ajax({
        type: 'get',
        url: '/categories',
        success: function(categories) {
          response.categories = categories
          let html = template('modifyPostTpl',response)
          $('.FormBox').html(html)
        }
      })
     
    }
  })
}
// 文章修改提交
$('.FormBox').on('submit','#ModifypostsForm',function() {
  let formdata = $(this).serialize()
  let id = $(this).attr('data-id')
  console.log(id);
  $.ajax({
    type: 'put',
    url: '/posts/'+ id,
    data: formdata,
    success: function(response) {
      location.href = "/admin/articleAll.html"
    }
  })
  return false
})
